﻿using System;
using System.Security.Cryptography;
using System.Text;
namespace Yt.Core.Security
{
    /// <summary>
    /// RSA非对称加密算法
    /// </summary>
    public class RSA
    {
        public static string EncryptString(string str, string key)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(Convert.FromBase64String(key));
            byte[] cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(str), false);
            return Convert.ToBase64String(cipherbytes);
        }
        public static string DecryptString(string encryptedstr, string key)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportCspBlob(Convert.FromBase64String(key));
            byte[] cipherbytes = rsa.Decrypt(Convert.FromBase64String(encryptedstr), false);

            return Encoding.UTF8.GetString(cipherbytes);
        }
        /// <summary>
        /// 生成密钥对
        /// </summary>
        /// <returns></returns>
        public static Keys GenerateKeys()
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            return new Keys(Convert.ToBase64String(RSA.ExportCspBlob(false)), Convert.ToBase64String(RSA.ExportCspBlob(true)));
        }
    }
}
